package com.xs.gis.cover.util;

import org.gdal.ogr.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: bo
 * @create: 2025-07-02 10:55
 */
public class GdbUtils {

    /**
     * 根据文件路径获取gdb数据源对象
     *
     * @param filePath，gdb数据路径
     * @param type，0为只读，1为可写
     * @author 415411
     * @create 2024/9/7
     **/
    public static DataSource GetDataSourceByGdbFilePath(String filePath, Integer type) {
        Driver driver = ogr.GetDriverByName("OpenFileGDB"); //设置驱动
        return driver.Open(filePath, type);
    }

    // 获取gdb图层个数
    public static int getGdbLayerCount(String gdbFilePath) {
        DataSource gdbSource = GetDataSourceByGdbFilePath(gdbFilePath, 0);
        return gdbSource.GetLayerCount();
    }

    // 获取gdb各个图层名称
    public static List<String> getGdbLayerNames(String gdbFilePath) {
        List<String> layerNames = new ArrayList<>();
        DataSource gdbSource = GetDataSourceByGdbFilePath(gdbFilePath, 0);
        for (int i = 0; i < gdbSource.GetLayerCount(); i++) {
            Layer layer = gdbSource.GetLayer(i);
            String layerName = layer.GetName();
            layerNames.add(layerName);
        }
        gdbSource.delete();
        return layerNames;
    }

    /**
     * 根据图层名称获取对应的字段信息
     *
     * @param layerName，图层名称
     * @param gdbFilePath，数据路径
     * @author 415411
     * @create 2024/9/7
     **/
    public static List<Map<String, String>> getAttributeByLayerName(String layerName, String gdbFilePath) {
        List<Map<String, String>> fieldMap = new ArrayList<>();
        DataSource gdbSource = GetDataSourceByGdbFilePath(gdbFilePath, 0);
        // 获取图层
        Layer layer = gdbSource.GetLayerByName(layerName);
        FeatureDefn featureDefn = layer.GetLayerDefn();
        for (int i = 0; i < featureDefn.GetFieldCount(); i++) {
            FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
            // 得到属性字段类型
            int fieldType = fieldDefn.GetFieldType();
            //            System.out.println(fieldType);
            String fieldTypeName = fieldDefn.GetFieldTypeName(fieldType);
            System.out.println(fieldTypeName);
            // 得到属性字段名称
            String fieldName = fieldDefn.GetName();
            System.out.println(fieldName);
            Map<String, String> current = new HashMap<>();
            current.put(fieldTypeName, fieldName);
            fieldMap.add(current);
        }
        gdbSource.delete();
        return fieldMap;
    }

    public static void main(String[] args) {
        //        System.out.println(getGdbLayerNames("D:\\work\\testdata\\gdbdata\\output\\ctest.gdb"));
        //        System.out.println(getAllFeaturesFieldValueBtFieldName("mbstyle_cookbook_line", "name","D:\\work\\testdata\\gdbdata\\output\\ctest.gdb"));
        System.out.println(getGdbLayerCount("D:\\work\\testdata\\gdbdata\\output\\ctest.gdb"));
    }


}
